package common

import (
	"context"
	"time"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
)

// 实例化后的rd
var rdClient *redis.Client

func RdclientInit() (*redis.Client, error) {
	rdClient = redis.NewClient(&redis.Options{
		Addr:     viper.GetString("redis.host") + ":" + viper.GetString("redis.port"),
		Password: viper.GetString("redis.redis_password"),
		DB:       0,
	})
	// 测试连接
	_, err := rdClient.Ping(context.Background()).Result()
	if err != nil {
		return nil, err
	}
	return rdClient, nil
}

func RdSet(key string, val string, expire string) error {
	return rdClient.Set(context.Background(), key, val, viper.GetDuration(expire)*time.Hour).Err()
}

func RdGet(key string) (string, error) {
	return rdClient.Get(context.Background(), key).Result()
}

func RdRm(key ...string) error {
	return rdClient.Del(context.Background(), key...).Err()
}
